package com.cong.nio.echo;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.spi.AbstractSelector;
import java.nio.channels.spi.SelectorProvider;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author cong
 * <p>
 * created on 2021/3/19 下午8:22
 */
public class MyEcho {
    private Selector selector;

    private ExecutorService tp= Executors.newCachedThreadPool();
    public static Map<Socket,Long> time_stat=new HashMap<Socket,Long>(10240);

    private void startServer() throws IOException {
        AbstractSelector selector = SelectorProvider.provider().openSelector();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);

        InetSocketAddress isa = new InetSocketAddress(InetAddress.getLocalHost(), 8000);
//        InetSocketAddress isa = new InetSocketAddress(8000);
        ssc.socket().bind(isa);

        SelectionKey key = ssc.register(selector, SelectionKey.OP_ACCEPT);
        for (;;){
            selector.select();
            Set<SelectionKey> readyKeys = selector.selectedKeys();
            Iterator<SelectionKey> i = readyKeys.iterator();
            long e =0;
            while (i.hasNext()){
                SelectionKey sk = i.next();
                i.remove();
                
                if (sk.isAcceptable()){
                    doAccept(sk);
                }
            }
        }

    }

    private void doAccept(SelectionKey sk) {
    }
}
